<template>
  <form @submit.prevent="handleSubmit" class="contact-form">
    <!-- 表单消息提示 -->
    <div v-if="message.show" class="form-message" :class="message.type">
      {{ message.text }}
    </div>
    
    <div class="form-row">
      <!-- 姓名输入 -->
      <div class="form-group col-md-6">
        <label for="name" class="form-label">您的姓名</label>
        <input
          id="name"
          v-model="form.name"
          type="text"
          class="form-control"
          :class="{ 'is-invalid': errors.name }"
          placeholder="请输入您的姓名"
          required
        >
        <div v-if="errors.name" class="invalid-feedback">
          {{ errors.name }}
        </div>
      </div>
      
      <!-- 邮箱输入 -->
      <div class="form-group col-md-6">
        <label for="email" class="form-label">电子邮箱</label>
        <input
          id="email"
          v-model="form.email"
          type="email"
          class="form-control"
          :class="{ 'is-invalid': errors.email }"
          placeholder="请输入您的邮箱"
          required
        >
        <div v-if="errors.email" class="invalid-feedback">
          {{ errors.email }}
        </div>
      </div>
    </div>
    
    <!-- 电话输入 -->
    <div class="form-group">
      <label for="phone" class="form-label">联系电话</label>
      <input
        id="phone"
        v-model="form.phone"
        type="tel"
        class="form-control"
        :class="{ 'is-invalid': errors.phone }"
        placeholder="请输入您的电话"
      >
      <div v-if="errors.phone" class="invalid-feedback">
        {{ errors.phone }}
      </div>
    </div>
    
    <!-- 主题选择 -->
    <div class="form-group">
      <label for="subject" class="form-label">咨询主题</label>
      <select
        id="subject"
        v-model="form.subject"
        class="form-control"
        :class="{ 'is-invalid': errors.subject }"
        required
      >
        <option value="" disabled>请选择咨询主题</option>
        <option value="product">产品咨询</option>
        <option value="cooperation">合作咨询</option>
        <option value="technical">技术支持</option>
        <option value="other">其他</option>
      </select>
      <div v-if="errors.subject" class="invalid-feedback">
        {{ errors.subject }}
      </div>
    </div>
    
    <!-- 详细内容 -->
    <div class="form-group">
      <label for="message" class="form-label">详细内容</label>
      <textarea
        id="message"
        v-model="form.message"
        class="form-control"
        :class="{ 'is-invalid': errors.message }"
        rows="5"
        placeholder="请输入您的详细需求..."
        required
      ></textarea>
      <div v-if="errors.message" class="invalid-feedback">
        {{ errors.message }}
      </div>
    </div>
    
    <!-- 提交按钮 -->
    <div class="form-group">
      <button 
        type="submit" 
        class="btn btn-primary"
        :disabled="isSubmitting"
      >
        <span v-if="isSubmitting">
          <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
          提交中...
        </span>
        <span v-else>提交咨询</span>
      </button>
    </div>
  </form>
</template>

<script>
import { reactive, ref } from 'vue'
import axios from 'axios'
import { useToast } from 'vue-toast-notification'
import 'vue-toast-notification/dist/theme-sugar.css'

export default {
  name: 'ContactForm',
  
  setup() {
    // 表单数据
    const form = reactive({
      name: '',
      email: '',
      phone: '',
      subject: '',
      message: ''
    })
    
    // 表单错误信息
    const errors = reactive({
      name: '',
      email: '',
      phone: '',
      subject: '',
      message: ''
    })
    
    // 表单状态
    const isSubmitting = ref(false)
    const message = reactive({
      show: false,
      type: '', // 'success' 或 'error'
      text: ''
    })
    
    // 初始化Toast通知
    const toast = useToast()
    
    // 表单验证方法
    const validateForm = () => {
      let isValid = true
      
      // 重置错误信息
      Object.keys(errors).forEach(key => {
        errors[key] = ''
      })
      
      // 验证姓名
      if (!form.name.trim()) {
        errors.name = '请输入您的姓名'
        isValid = false
      } else if (form.name.length < 2) {
        errors.name = '姓名至少需要2个字符'
        isValid = false
      }
      
      // 验证邮箱
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!form.email) {
        errors.email = '请输入您的邮箱'
        isValid = false
      } else if (!emailRegex.test(form.email)) {
        errors.email = '请输入有效的邮箱地址'
        isValid = false
      }
      
      // 验证电话（可选）
      if (form.phone && !/^[\d\s+-]+$/.test(form.phone)) {
        errors.phone = '请输入有效的电话号码'
        isValid = false
      }
      
      // 验证主题
      if (!form.subject) {
        errors.subject = '请选择咨询主题'
        isValid = false
      }
      
      // 验证消息内容
      if (!form.message.trim()) {
        errors.message = '请输入咨询内容'
        isValid = false
      } else if (form.message.length < 10) {
        errors.message = '内容至少需要10个字符'
        isValid = false
      }
      
      return isValid
    }
    
    // 提交表单处理
    const handleSubmit = async () => {
      // 验证表单
      if (!validateForm()) {
        return
      }
      
      // 设置提交状态
      isSubmitting.value = true
      message.show = false
      
      try {
        // 发送表单数据到服务器
        const response = await axios.post('/api/contact', form)
        
        // 处理成功响应
        if (response.data.success) {
          // 显示成功消息
          toast.success('提交成功！我们将尽快与您联系', {
            position: 'top-right',
            duration: 5000
          })
          
          // 重置表单
          Object.keys(form).forEach(key => {
            form[key] = ''
          })
        } else {
          // 显示服务器返回的错误消息
          toast.error(response.data.message || '提交失败，请稍后重试', {
            position: 'top-right'
          })
        }
      } catch (error) {
        console.error('提交表单出错:', error)
        
        // 显示错误消息
        let errorMessage = '网络错误，请稍后重试'
        if (error.response) {
          // 服务器返回的错误
          errorMessage = error.response.data.message || errorMessage
        } else if (error.request) {
          // 请求已发出但没有响应
          errorMessage = '服务器未响应，请检查您的网络连接'
        }
        
        toast.error(errorMessage, {
          position: 'top-right'
        })
      } finally {
        // 重置提交状态
        isSubmitting.value = false
      }
    }
    
    // 暴露给模板的数据和方法
    return {
      form,
      errors,
      isSubmitting,
      message,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.contact-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

.form-label {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.form-control {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: all 0.3s;
}

.form-control:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
}

.is-invalid {
  border-color: #e74c3c;
}

.is-invalid:focus {
  box-shadow: 0 0 0 0.2rem rgba(231, 76, 60, 0.25);
}

.invalid-feedback {
  color: #e74c3c;
  font-size: 0.875em;
  margin-top: 5px;
}

.btn-primary {
  background-color: #3498db;
  border-color: #3498db;
  padding: 10px 25px;
  font-weight: 600;
  transition: all 0.3s;
}

.btn-primary:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.btn-primary:disabled {
  background-color: #95a5a6;
  border-color: #95a5a6;
  cursor: not-allowed;
}

.form-message {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.form-message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.form-message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

@media (max-width: 768px) {
  .contact-form {
    padding: 20px;
  }
}
</style>